package com.uxsino.simo.indicator.retractor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.uxsino.commons.utils.config.ConfigProp;
import com.uxsino.reactorq.model.INDICATOR_TYPE;
import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;
import com.uxsino.simo.query.QueryTemplate;

public class RegexValueRetractor extends SimpleValueRetractor {

    private Pattern pattern;

    @ConfigProp(name = "index")
    public int valueIndex;

    public RegexValueRetractor(INDICATOR_TYPE valueType) {
        super(valueType);
        valueIndex = 1;
    }

    @ConfigProp(name = "pattern", required = true, trim = false)
    public void setPattern(String regex) {
        pattern = Pattern.compile(regex);
    }

    @Override
    public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {
        assert obj instanceof String;
        String s = retreive((String) obj);

        if (s == null) {
            return null;
        }

        return convertValue(s);
    }

    public String retreive(String buf) {
        if (pattern == null) {
            return buf;
        }
        if (buf == null) {
            return null;
        }
        Matcher m = pattern.matcher(buf);

        if (m.find() && m.groupCount() >= valueIndex) {
            return m.group(valueIndex);
        }
        return null;
    }
}
